package team.scau.laboratory_repair.web.mobile.repair.web;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import team.scau.laboratory_repair.common.activiti.dto.RepairProcDto;
import team.scau.laboratory_repair.common.activiti.dto.RepairTaskDto;
import team.scau.laboratory_repair.common.base.BaseController;
import team.scau.laboratory_repair.common.enums.WechatUserType;
import team.scau.laboratory_repair.common.utils.StringTool;
import team.scau.laboratory_repair.service.NoteService;
import team.scau.laboratory_repair.service.RecordPhotoService;
import team.scau.laboratory_repair.service.RecordService;
import team.scau.laboratory_repair.service.RepairService;

@RequestMapping("/mobile/repair")
@Controller
@CommonsLog
public class ProcController extends BaseController {

    @Autowired
    private RecordService recordService;
    @Autowired
    private RepairService repairService;
    @Autowired
    private NoteService noteService;
    @Autowired
    private RecordPhotoService recordPhotoService;

    @GetMapping("/proc/{id}")
    public String getProcedure(Model model, @PathVariable("id") long recordId) {
        RepairProcDto dto;
        try {
            dto = repairService.selectProcByRecordId(recordId, getCUser(), getOpenId());

            String taskId = "";
            if(dto != null){
                String currentTaskName = dto.getTaskName();
                for(RepairTaskDto task : dto.getList()){
                    if(task.getTaskName().equals(currentTaskName)){
                        taskId = task.getId();
                        break;
                    }
                }
            }
            boolean isStaff = getWUser().getUserType() == WechatUserType.STAFF.getType(),
                    isLeader = getWUser().getUserType() == WechatUserType.LEADER.getType();
            if(isStaff) model.addAttribute("staffId", getCUser().getId());

            model.addAttribute("notes", noteService.listByIds(StringTool.strings2LongList((String)dto.getVars().get("notes"))));
            model.addAttribute("taskId", taskId);
            model.addAttribute("proc", dto);
            model.addAttribute("record", recordService.findById(recordId));
            model.addAttribute("isStaff", isStaff);
            model.addAttribute("isLeader", isLeader);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return "/mobile/repair/ShowProcedure";
    }
}
